#!/usr/bin/env python

# Copyright (c) 2008 Anthony Cramp
# Licensed under the MIT License
# See accompanying file LICENSE.txt or
# http://www.opensource.org/licenses/mit-license.php

import fed
import yaml
import copy
import sys

def createObjectClassTree(oc):
  ocdict = {"name": "", "attributes": [], "children": []}

  if type(oc) is dict:
    # oc is a dict so it has a solitary key (the oc name)
    # and a list as its value
    ocdict["name"] = oc.keys()[0]
    
    # the value list possibly contains a list in its first element
    # which will be a list of attributes. The rest will be new
    # object classes
    children = oc[ocdict["name"]]
    if None is children or len(children) == 0:
      # probably an error, but we'll let it pass
      pass
    elif type(children[0]) is list:
      # found an attribute list in the first entry
      ocdict["attributes"] = copy.copy(children[0])
      for c in children[1:]:
        # after the attribute list we just have sub object classes
        ocdict["children"].append(createObjectClassTree(c))
        
    else:
      # no attributes, just process sub object classes
      for c in children:
        ocdict["children"].append(createObjectClassTree(c))
        
  else:
    # just an object class without attributes or sub object classes
    ocdict["name"] = oc
    
  return ocdict
  
def createInteractionClassTree(ic):
  icdict = {"name": "", "parameters": [], "children": []}

  if type(ic) is dict:
    # ic is a dict so it has a solitary key (the ic name)
    # and a list as its value
    icdict["name"] = ic.keys()[0]

    # the value list possibly contains a list in its first element
    # which will be a list of parameters. The rest will be new
    # interaction classes
    children = ic[icdict["name"]]
    if None is children or len(children) == 0:
      # probably an error, but we'll let it pass
      pass
    elif type(children[0]) is list:
      # found a parameter list in the first entry
      icdict["parameters"] = copy.copy(children[0])
      for c in children[1:]:
        # after the parameter list we just have sub interaction classes
        icdict["children"].append(createInteractionClassTree(c))

    else:
      # no parameters, just process sub interaction classes
      for c in children:
        icdict["children"].append(createInteractionClassTree(c))

  else:
    # just an interaction class without parameters or sub interaction classes
    icdict["name"] = ic

  return icdict

def main():
  if len(sys.argv) != 2:
    print "Usage: python yaml2fed.py <in.yaml>"
    return
    
  f = file(sys.argv[1], 'r')
  d = yaml.load(f)

  name = d["name"]
  ocs = d["oc"]
  ics = d["ic"]

  objectClasses = [createObjectClassTree(oc) for oc in ocs]
  interactionClasses = [createInteractionClassTree(ic) for ic in ics]

  print fed.getFed(name, objectClasses, interactionClasses)
  
if __name__ == '__main__':
  main()
